package fr.labri.macchiato.feature.googleShopping;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.rpc.AsyncCallback;

import fr.labri.macchiato.core.technical.Callback;

public class GoogleQueryLauncher {

	private static final String GS_kEY = "AIzaSyBozSvgYRFlGb0JpQ2_7nLxA2Q3cO_I_H4";
	private final String BASE_URL;

	private RequestBuilder requestBuilder;
	private String queryResult;

	public GoogleQueryLauncher(String url) {
		BASE_URL = url;
	}
	
	private void sendQuery(String query, final Callback<String> callback)
			throws RequestException {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(BASE_URL).append("key=").append(GS_kEY)
				.append("&country=fr").append("&q=").append(query).append("&alt=json");

		requestBuilder = new RequestBuilder(RequestBuilder.GET, stringBuilder.toString());
		queryResult = null;
		requestBuilder.sendRequest(stringBuilder.toString(),
				new RequestCallback() {
					public void onResponseReceived(Request request,
							Response response) {
						queryResult = response.getText();
						callback.onCallback(queryResult);
					}

					public void onError(Request request, Throwable exception) {
						exception.printStackTrace();
					}
				});
	}

	public void launchQueryForArticles(String query,
			final AsyncCallback<String> callback) {

		try {
			sendQuery(query, new Callback<String>() {

				@Override
				public void onCallback(String result) {
					callback.onSuccess(result);

				}
			});
		} catch (RequestException e) {

			callback.onFailure(e);
		}
	}

	public void launchQueryForOffers(String ean,
			final AsyncCallback<String> callback) {
		try {
			String query = buildOffersQuery(ean);
			sendQuery(query, new Callback<String>() {

				@Override
				public void onCallback(String result) {
					callback.onSuccess(result);

				}
			});
		} catch (RequestException e) {

			callback.onFailure(e);
		}
		
	}

	private String buildOffersQuery(String ean) {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(BASE_URL).append("key=").append(GS_kEY)
				.append("&country=fr").append("&gtin=").append(ean).append("&alt=json");
		return stringBuilder.toString();
	}

//	/**
//	 * Get articles
//	 */
//	public void onRequestComplete(JavaScriptObject json) {
//		List<Article> results = null;
//
//		JSONObject j = new JSONObject(json);
//		// Get statistics for the search results (item count and merchants
//		// count)
//		// int totalItems = 00;
//		ArrayList<String> merchantsNameList = new ArrayList<String>();
//
//		// iterate over each entry in the feed
//		Article _article = null;
//		JSONNumber totalitems = (JSONNumber) j.get("totalItems");
//
//		JSONArray items = (JSONArray) j.get("items");
//		// JSONArray entries = (JSONArray) feed.get("product");
//		for (int i = 0; i < items.size(); ++i) {// items.size() TODO replace
//												// this
//			// find products (array)
//			JSONObject metaProduct = (JSONObject) items.get(i); // the product
//																// object is
//																// encapsulated
//																// in another
//																// product
//																// object
//																// 'metaProduct'
//			if (metaProduct != null) {
//				JSONObject jsonProduct = (JSONObject) metaProduct
//						.get("product");
//				// create result object with collected fields
//				// ArrayList<BusinessProvider> merchantList = new
//				// ArrayList<BusinessProvider>();
//
//				JSONString title = (JSONString) jsonProduct.get("title");
//				JSONString gtin = (JSONString) jsonProduct.get("gtin");
//				String ean = "";
//				if (gtin != null)
//					ean = gtin.stringValue();
//				ean = format13EAN(ean);
//				JSONString description = (JSONString) jsonProduct
//						.get("description");
//				JSONString link = (JSONString) jsonProduct.get("link");
//
//				// Calculate the number of found merchants
//				// TODO calculate form the merchant list directly
//				JSONObject author = (JSONObject) jsonProduct.get("author");
//				JSONString merchantName = (JSONString) author.get("name");
//				if (!merchantsNameList.contains(merchantName.stringValue()))
//					merchantsNameList.add(merchantName.stringValue());
//
//				JSONArray inventories = (JSONArray) jsonProduct
//						.get("inventories");
//				// BusinessProvider aProvider = null;
//				for (int k = 0; k < inventories.size(); k++) {
//					JSONObject merchant = (JSONObject) inventories.get(k);
//					if (merchant != null) {
//						JSONString availability = (JSONString) merchant
//								.get("availability");
//						JSONString channel = (JSONString) merchant
//								.get("channel");
//						JSONString currency = (JSONString) merchant
//								.get("currency");
//						JSONNumber price = (JSONNumber) merchant.get("price");
//						// // aProvider = new
//						// BusinessProvider(merchantName.stringValue(), // name
//						// price.doubleValue(),
//						// currency.stringValue(),
//						// availability.stringValue(),
//						// channel.stringValue());
//					}
//					// merchantList.add(aProvider);
//				}
//				// getting images liks
//				ArrayList<String> imageList = new ArrayList<String>();
//				JSONArray imageLinks = (JSONArray) jsonProduct.get("images");
//				for (int k = 0; k < imageLinks.size(); k++) {
//					JSONObject image = (JSONObject) imageLinks.get(k);
//					if (image != null) {
//						JSONString imageLink = (JSONString) image.get("link");
//						imageList.add(imageLink.stringValue());
//					}
//
//				}
//				// if (title != null && description != null && link != null
//				// && !merchantList.isEmpty() && !imageList.isEmpty())
//				// result = new Product(title.stringValue(),
//				// description.stringValue(), link.stringValue(),
//				// imageList, merchantList);
//				_article = new Article(ean, title.stringValue());
//				results.add(_article);
//				// else break;
//			}
//			// check the consistency of the result (all fields are filled
//			// if(result.isValid())
//			// getView().addSearchResult(result);
//		}
//		// getView().addSearchStats(totalitems+"",merchantsNameList.size() );
//		// getView().printResults();
//		googleSearch.addModels(results);
//	}
//
//	/**
//	 * @param ean
//	 */
//	private String format13EAN(String ean) {
//		int size = ean.length();
//		if (size == 13)
//			return ean;
//		if (size > 13)
//			return ean.substring(size - 13);
//		else
//			return format13EAN("0000000000000" + ean);
//	}

}
